package cn.wolfcode.trip.app.controller;

import cn.wolfcode.trip.base.domain.Region;
import cn.wolfcode.trip.base.domain.Strategy;
import cn.wolfcode.trip.base.query.StrategyQueryObject;
import cn.wolfcode.trip.base.service.IRegionService;
import cn.wolfcode.trip.base.service.IStrategyService;
import com.github.pagehelper.PageInfo;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("regions")
public class RegionController {
    @Autowired
    private IRegionService regionService;
    @Autowired
    private IStrategyService strategyService;
    @Autowired
    private ServletContext context;

    @GetMapping
    public List<Region> listAll(Integer state){
        List<Region> regions = regionService.listAll(state);
        return regionService.listAll(state);
    }

    @GetMapping(value = "/{regionId}/strategies",produces = "text/html;chartset:utf-8")
    public void listStrategiesHtml(StrategyQueryObject qo, HttpServletResponse response) throws Exception {
        //不分页
        qo.setPageSize(0);
        qo.setState(Strategy.TYPE_RECOMMEND);
        PageInfo<?> commends = strategyService.query(qo);
        //全部攻略
        qo.setPageSize(6);
        qo.setState(null);
        PageInfo<?> query = strategyService.query(qo);

        //使用freemaker
        Configuration config = new Configuration(Configuration.VERSION_2_3_23);
        config.setDirectoryForTemplateLoading(new File(context.getRealPath("/template")));
        Template template = config.getTemplate("strategyTemplate.ftl", "utf-8");
        HashMap<Object, Object> map = new HashMap<>();
        map.put("commends",commends);
        map.put("query",query);
        template.process(map,response.getWriter());
    }

    @GetMapping(value = "/{regionId}/strategies",produces = "application/json;chartset:utf-8")
    public PageInfo<?> listStrategiesJson(StrategyQueryObject qo){
        qo.setPageSize(6);
        qo.setState(null);
        return strategyService.query(qo);
    }
}
